//
//  XYStatusViewModel.swift
//  WeiboSourceCode
//
//  Created by 周星宇 on 16/1/1.
//  Copyright © 2016年 cn.weibo. All rights reserved.
//

import UIKit

class XYStatusViewModel: NSObject {

    var status: XYStatus? {
        
        didSet {
            
            // 计算会员要显示的图片
            if let mbrank = status?.user?.mbrank where mbrank > 0 && mbrank < 7{
                memberImage = UIImage(named: "common_icon_membership_level\(mbrank)")
            }else{
                memberImage = nil
            }
            // 设置认证图标
            verifiedImage = getVerifiedImage()
            // 转发评论赞要显示的字符串
            repostsCount = getStatusCount(status?.reposts_count ?? 0, defaultTitle: "转发")
            commentsCount = getStatusCount(status?.comments_count ?? 0, defaultTitle: "评论")
            attitudesCount = getStatusCount(status?.attitudes_count ?? 0, defaultTitle: "赞")
            // 判断是否有转发微博
            if let retweetText = status?.retweeted_status?.text {
                if let name = status?.retweeted_status?.user?.screen_name {
                    retweetStatusText = "@\(name):\(retweetText)"
                    let result = dealStatusText(retweetStatusText)
                    retweetMatchAttributeText = result.attr
                    retweetMatchResults = result.mathResult
                }
            }
            // 判断原创微博是否有图片
            if let urls = status?.pic_urls where urls.count > 0 {
                picUrls = urls
            }else if let urls = status?.retweeted_status?.pic_urls where urls.count > 0 {
                // 判断转发微博是否有图片
                picUrls = urls
            }
            // 处理来源文字
            guard let st = status?.source else {
                return
            }
            if let startRange = st.rangeOfString("\">") {
                if let endRange = st.rangeOfString("</"){
                    sourceText = "来自 \(st.substringWithRange(startRange.endIndex..<endRange.startIndex))"
                }
            }
            // 处理原创微博的图文混排
            let result = dealStatusText(status?.text)
            originalStatusAttributeText = result.attr
            originalMatchResults = result.mathResult
            // 根据模型，来生成缩略图的数组
            
            if let urls = status!.retweeted_status?.pic_urls ?? status!.pic_urls {
                
                // 创建缩略图数组
                thumbnailUrls = [NSURL]()
                
                // 遍历字典数组
                for dict in urls {
                    
                    // 因为字典是按照 key 来取值，如果 key 错误，会返回 nil
                    let url = NSURL(string: dict.thumbnail_pic!)
                    
                    // 相信服务器返回的 url 字符串一定能够生成
                    thumbnailUrls?.append(url!)
                }
            }

        }
    }
    /// 缩略图URL数组 - 存储型属性 !!!
    /// 如果是原创微博，可以有图，可以没有图
    /// 如果是转发微博，一定没有图，retweeted_status 中，可以有图，也可以没有图
    /// 一条微博，最多只有一个 pic_urls 数组
    var thumbnailUrls: [NSURL]?
    // 原创微博attribute  
    var originalStatusAttributeText: NSAttributedString?
    // 转发微博attribute
    var retweetMatchAttributeText :NSAttributedString?
    // 原创微博的特殊字符的匹配结果
    var originalMatchResults: [XYMatchResult]?
    
    var retweetMatchResults: [XYMatchResult]?
    // 当前微博的图片组
    var picUrls: [XYHomePicture]?
    var memberImage: UIImage?
    var verifiedImage: UIImage?
    
    // 转发评论赞的显示数量逻辑
    
    var repostsCount: String?
    var commentsCount: String?
    var attitudesCount: String?
    var sourceText: String?
    var timeText: String? {
        return NSDate.sinaDate(status?.created_at)?.sinaDateDescription
    }
    /// 转发微博的内容(如果有转发微博的话，这个属性才有意义)
    var retweetStatusText: String? // @昵称: 转发微博的内容
    // 处理微博的文字  返回匹配到的特殊字符的数组 以及 富文本
    private func dealStatusText(contentText:String?) -> (attr: NSMutableAttributedString?, mathResult: [XYMatchResult]?) {
        
        guard let text = contentText else{
            return (nil,nil)
        }
        let originalAttributeStr = NSMutableAttributedString(string: text)
        // 创建存储匹配结果的容器
        var results = [XYMatchResult]()
        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z\\u4e00-\\u9fa5]+\\]") { (count, captureString, captureRange, _) -> Void in
            // 把匹配结果生成模型
            let matchResult = XYMatchResult(captureString: captureString.memory! as String, captureRange: captureRange.memory)
            results.append(matchResult)
        }
        // 返转替换
        for value in results.reverse() {
            //通过chs文字找到对应表情
            if let emoticon = XYEmoticonTool.sharedEmoticonTool.emoticonWithChs(value.captureString) {
                // 如果找到
                let attachment = XYTextAttachment()
                let attr = attachment.attrubutedStringWith(emoticon, font: UIFont.systemFontOfSize(XYStatusCellFontSize))
                // 替换
                originalAttributeStr.replaceCharactersInRange(value.captureRange, withAttributedString: attr)
            }
        }
        // 添加字体大小
        originalAttributeStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(XYStatusCellFontSize), range: NSMakeRange(0, originalAttributeStr.length))
        let highLightTextResults = addHighLighted(originalAttributeStr)
        
        return (originalAttributeStr, highLightTextResults)
    }
    // 匹配高亮文字
    private func addHighLighted(attr: NSMutableAttributedString) -> [XYMatchResult]{
     
        // 保存匹配结果的数组
        var matchResults = [XYMatchResult]()
        (attr.string as NSString).enumerateStringsMatchedByRegex("@[^\\W]+") { (count, captureString, captureRange, _) -> Void in
            // 创建结果模型
            attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: captureRange.memory)
            let matchResult = XYMatchResult(captureString: captureString.memory! as String, captureRange: captureRange.memory)
            matchResults.append(matchResult)
        }
        // 匹配话题
        (attr.string as NSString).enumerateStringsMatchedByRegex("#[^#]+#") {(count, captureString, captureRange, _) -> Void in
            attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: captureRange.memory)
            
            // 生成匹配结果的模型
            let matchResult = XYMatchResult(captureString: captureString.memory! as String, captureRange: captureRange.memory)
            matchResults.append(matchResult)
        }
        
        // 匹配链接
        (attr.string as NSString).enumerateStringsMatchedByRegex("http://[^\\s^\\u4e00-\\u9fa5]+") {(count, captureString, captureRange, _) -> Void in
            attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: captureRange.memory)
            
            // 生成匹配结果的模型
            let matchResult = XYMatchResult(captureString: captureString.memory! as String, captureRange: captureRange.memory)
            matchResults.append(matchResult)
        }
        
        return matchResults
    }
    private func getVerifiedImage() -> UIImage? {
        
        if let verifiedType = status?.user?.verified_type {
            
            switch verifiedType {
            case -1:
                return nil
            case 0:
                return UIImage(named: "avatar_vip")
            case 2,3,5:
                return UIImage(named: "avatar_enterprise_vip")
            case 220:
                return UIImage(named: "avatar_grassroot")
            default:
                return nil
            }
        }
        return nil
    }
    private func getStatusCount(count: Int, defaultTitle: String) -> String {
        
        /**
        - 比如转发数量为 9990 --> 9990
        - 大于万 11111 --> 1.1 万
        - 大于万 10900 --> 1万
        */
        // 计算显示什么字符串
        
        // let count = status?.reposts_count ?? 0
        
        if count == 0 {
            return defaultTitle
        }
        
        if count < 10000 {
            return "\(count)"
        }else{
            // 先除以1000
            let result = CGFloat(count / 1000) / 10
            let resultStr = "\(result)万"
            if resultStr.containsString(".0"){
                return resultStr.stringByReplacingOccurrencesOfString(".0", withString: "")
            }
            return resultStr
        }
    }
    
    
    
    
}
